<?php
/**********************************************************************//**\file
	Armory Cache Database

	Description:  Caches data fetched from the net in the local database
*******************************************************************************/

	class armorycache
	{
		protected $cache_method;
		protected $cache_folder;
		protected $type;

		public function __construct($type, $method = null, $cache_folder = null)
		{
			GLOBAL $config;

			if(is_null($method))
			{
				$this->cache_method = $config['cache_method'];
			}
			if(is_null($cache_folder))
			{
				$this->cache_folder = $config['cache_folder'];
			}

			$this->type = $type;
		}

		public function cache($name, $data)
		{
			if($this->cache_method == 'filesystem')
			{
				$this->filesystem($name, $data);
			}
			elseif($this->cache_method == 'database')
			{
				$this->database($name, $data);
			}
			else
			{
				die('invalid cache method');
			}
		}

		protected function filesystem($name, $data)
		{
			$path = dirname(__FILE__).'/../'.$this->cache_folder.'/'.$this->type.'/'.$name.'.xml';

			file_put_contents($path, $data);
		}

		protected function database($name, $data)
		{
			$db = new armorydb();
			$time = time();

			$data = $db->mysqli->real_escape_string($data);

			$db->query("SELECT cache_name FROM armory_cache WHERE cache_name = '$name' AND cache_type = '{$this->type}'");

			if(is_null($db->result()))
			{
				# Create a new record
				$db->query("INSERT INTO armory_cache SET cache_type = '{$this->type}', cache_name = '$name', cache_timestamp = $time, cache_data = '$data'");
			}
			else
			{
				# Update extant record
				$db->query("UPDATE armory_cache SET cache_type = '{$this->type}', cache_timestamp = $time, cache_data = '$data' WHERE cache_name = '$name' LIMIT 1");
			}


			unset($db);
		}
	}
	
?>
